package com.zj.ssm.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @Author: Guaniu
 * @Date: 2022/2/17 8:27
 * @Version 1.0
 */
@Service
public class SOSSUtil {

    public  String uploadfile (MultipartFile multipartFile, String dir){

        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5t7cbrrzF2aProCEGW4n";
        String accessKeySecret = "jUAxT7tGiEUcafVnkJvOsVLwxWb7kw";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "qy14610";
        // 填写文件名。文件名包含路径，不包含Bucket名称。例如exampledir/exampleobject.txt。
        OSS ossClient = null;
       try{
           ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

           if(!ossClient.doesBucketExist(bucketName)){
               ossClient.createBucket(bucketName);
               ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
           }

           InputStream inputStream = multipartFile.getInputStream();
           SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MMM/dd");
           String datePath = dateFormat.format(new Date());
           String originnname = multipartFile.getOriginalFilename();
           String filename = UUID.randomUUID().toString();
           String suffix = originnname.substring(originnname.lastIndexOf("."));
           String newName = filename + suffix;
           String fileUrl =dir+ "/" + datePath + "/" +newName;

           ossClient.putObject(bucketName, fileUrl, inputStream);
           return "https://" +bucketName+ "." +endpoint+ "/" +fileUrl;
// 关闭OSSClient。
       }catch (Exception e){
           e.printStackTrace();
           return "file";
       }finally{
           ossClient.shutdown();
       }

    }


}
